﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using Moonlite.ExtensionApi.XimlInterfaces;

namespace Moonlite.Platform.Ximl
{
    public class IconNodeDataProvider : INodeDataProvider
    {
        public bool ParseXimlNode(ref IXimlNode node, out DescriptorBase descriptor)
        {
            descriptor = null;
            if (node.Name == "Image")
            {
                if (XimlTree.Instance.CurrentAssembly == null)
                {
                    throw new NoAssemblyContextException("No valid assembly context found.");
                }
                if (string.IsNullOrEmpty(node["resource"]))
                {
                    throw new XimlInvalidElementException("The Image Ximl element must have attribute resource.");
                }
                node["resource"] = node["resource"].TrimStart(new char[] { '$' });
                if (ResourceManager.ResourceExists(node["resource"], ResourceTypes.ImageType) || ResourceManager.ResourceExists(node["resource"], ResourceTypes.StringType))
                {
                    throw new XimlException("The resource at " + node["resource"] + " already exists.");
                }
                Stream stream = ResourceManager.GetStream(node["path"], XimlTree.Instance.CurrentAssembly);
                Image image = Image.FromStream(stream);
                if (image != null)
                {
                    XimlTree.Instance.Resources.Add(node["resource"], image);
                }
            }
            return false;
        }
    }
}
